package com.lmx.persistence.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.EvaluateExamerAnswer;
import com.lmx.repoDomain.tmodel.EvaluateResult;

/**
 * EvaluateResultService实现
 *
 * @author ytche
 * @date 2017年8月22日
 *
 */
@Service
public class EvaluateResultServiceImpl extends BaseCrudServiceImpl<EvaluateResult> implements
		EvaluateResultService {
	@Autowired
	private EvaluateExamerAnswerService answerService;

	@Override
	public EvaluateResult save(EvaluateResult entity) {
		if (CommonConstants.DEFAULT_STATUS_YES_1.equals(entity.getCompleteStatus())
				&& StringUtils.isNotBlank(entity.getScore())) {
			this.updateScore(entity);
		}
		return super.save(entity);
	}

	@Override
	public void updateScore(EvaluateExamerAnswer entity) {
		Session session = super.em.unwrap(Session.class);
		EvaluateResult result = super.findOne(entity.getResult().getId());
		this.updateScore(result);
		super.save(result);
		session.flush();
		entity.setResult(result);
	}

	private void updateScore(EvaluateResult result) {
		List<EvaluateExamerAnswer> answers = this.answerService.findNotDelete("result.id",
				result.getId());
		Integer score = 0;
		for (EvaluateExamerAnswer answer : answers) {
			String anwserScore = answer.getAnswer().getScore();
			if (!StringUtils.isNumeric(anwserScore)) {
				continue;
			}
			score += Integer.valueOf(answer.getAnswer().getScore());
		}
		result.setScore(new Integer(score).toString());
	}
}
